/**
 * 紧急处理大图片脚本 v2
 * 修复了路径处理问题
 */
const fs = require('fs');
const path = require('path');
const sharp = require('sharp');

// 需要紧急处理的大图片列表
const URGENT_IMAGES = [
  'miniprogram/images/news/spring-food.jpg',        // 219.79 KB
  'miniprogram/images/discovers/png/yidalimina.png', // 135.92 KB
  'miniprogram/images/meals/breakfast3.png',         // 123.07 KB
  'miniprogram/images/discovers/png/yumipaigu.png',  // 117.85 KB
  'miniprogram/images/discovers/png/caomeisuannai.png', // 84.87 KB
  'miniprogram/images/meals/dinner3.png',            // 84.78 KB
  'miniprogram/images/discovers/png/xiangguqingcai.png', // 78.17 KB
  'miniprogram/images/discovers/png/kaojixiong.png', // 76.68 KB
  'miniprogram/images/discovers/png/danbaizhinengliangbing.png', // 67.41 KB
  'miniprogram/images/discovers/png/shuiguoshala.png' // 66.12 KB
];

// 设置目标大小上限(KB)
const TARGET_SIZE = 49; // 保守设置在50KB以下

// 创建输出目录和备份目录
const URGENT_OUTPUT_DIR = 'urgent_fixed_images';
const BACKUP_DIR = 'image_backups';

if (!fs.existsSync(URGENT_OUTPUT_DIR)) {
  fs.mkdirSync(URGENT_OUTPUT_DIR);
}

if (!fs.existsSync(BACKUP_DIR)) {
  fs.mkdirSync(BACKUP_DIR);
}

// 获取文件大小(KB)
function getFileSizeInKB(filePath) {
  try {
    const stats = fs.statSync(filePath);
    return stats.size / 1024;
  } catch (error) {
    console.error(`获取文件大小失败: ${filePath}`, error);
    return 0;
  }
}

// 压缩单个图片
async function compressUrgentImage(imagePath) {
  try {
    // 检查文件是否存在
    if (!fs.existsSync(imagePath)) {
      console.log(`文件不存在: ${imagePath}`);
      return { path: imagePath, status: 'not_found' };
    }

    const fileName = path.basename(imagePath);
    // 使用简单的备份文件名，避免路径问题
    const backupPath = path.join(BACKUP_DIR, fileName + '.bak');
    const outputPath = path.join(URGENT_OUTPUT_DIR, fileName);
    
    // 备份原始文件
    fs.copyFileSync(imagePath, backupPath);
    console.log(`已备份原始文件到: ${backupPath}`);
    
    const originalSize = getFileSizeInKB(imagePath);
    console.log(`处理图片: ${imagePath} (${originalSize.toFixed(2)}KB)`);

    // 获取图片格式
    const ext = path.extname(imagePath).toLowerCase();
    
    // 加载图片
    let image = sharp(imagePath);
    const metadata = await image.metadata();
    
    // 初始压缩参数
    let quality = 70;
    
    // 根据原始大小决定缩放比例
    let scale = 1.0;
    if (originalSize > 150) {
      scale = 0.5; // 缩小到原来的50%
    } else if (originalSize > 100) {
      scale = 0.6; // 缩小到原来的60%
    } else if (originalSize > 70) {
      scale = 0.7; // 缩小到原来的70%
    } else {
      scale = 0.8; // 缩小到原来的80%
    }
    
    let width = Math.floor(metadata.width * scale);
    
    console.log(`  原始尺寸: ${metadata.width}x${metadata.height}`);
    console.log(`  目标尺寸: ${width}x${Math.floor(metadata.height * scale)}`);
    
    // 压缩图片
    let buffer;
    if (ext === '.jpg' || ext === '.jpeg') {
      buffer = await image
        .resize(width)
        .jpeg({ quality })
        .toBuffer();
    } else if (ext === '.png') {
      buffer = await image
        .resize(width)
        .png({ quality })
        .toBuffer();
    } else {
      buffer = await image
        .resize(width)
        .webp({ quality })
        .toBuffer();
    }
    
    // 检查压缩后大小
    let compressedSize = buffer.length / 1024;
    console.log(`  第一次压缩: ${compressedSize.toFixed(2)}KB`);
    
    // 如果还是太大，继续压缩
    let attempts = 1;
    while (compressedSize > TARGET_SIZE && attempts < 5) {
      attempts++;
      
      // 降低质量和尺寸
      quality = Math.max(quality - 10, 40);
      scale = scale * 0.9;
      width = Math.floor(metadata.width * scale);
      
      console.log(`  再次尝试: 质量=${quality}, 宽度=${width}px`);
      
      // 重新压缩
      if (ext === '.jpg' || ext === '.jpeg') {
        buffer = await image
          .resize(width)
          .jpeg({ quality })
          .toBuffer();
      } else if (ext === '.png') {
        buffer = await image
          .resize(width)
          .png({ quality })
          .toBuffer();
      } else {
        buffer = await image
          .resize(width)
          .webp({ quality })
          .toBuffer();
      }
      
      compressedSize = buffer.length / 1024;
      console.log(`  第${attempts}次压缩: ${compressedSize.toFixed(2)}KB`);
    }
    
    // 如果PNG还是太大，尝试转为JPEG
    if (compressedSize > TARGET_SIZE && (ext === '.png')) {
      console.log(`  尝试转换为JPEG格式...`);
      buffer = await image
        .resize(width)
        .jpeg({ quality: 60 })
        .toBuffer();
      
      compressedSize = buffer.length / 1024;
      console.log(`  转换为JPEG后: ${compressedSize.toFixed(2)}KB`);
    }
    
    // 保存压缩后的图片
    fs.writeFileSync(outputPath, buffer);
    console.log(`  保存到输出目录: ${outputPath}`);
    
    // 直接替换原始文件
    fs.writeFileSync(imagePath, buffer);
    console.log(`  替换原始文件`);
    
    // 计算减少比例
    const reduction = originalSize - compressedSize;
    const reductionPercent = (reduction / originalSize) * 100;
    
    console.log(`  压缩结果: ${originalSize.toFixed(2)}KB -> ${compressedSize.toFixed(2)}KB (减少 ${reduction.toFixed(2)}KB, ${reductionPercent.toFixed(2)}%)`);
    
    return {
      path: imagePath,
      originalSize,
      newSize: compressedSize,
      reduction,
      status: 'success'
    };
  } catch (error) {
    console.error(`处理图片失败: ${imagePath}`, error);
    return {
      path: imagePath,
      error: error.message,
      status: 'error'
    };
  }
}

// 主函数
async function main() {
  console.log('开始紧急处理大图片...');
  
  let totalOriginalSize = 0;
  let totalNewSize = 0;
  let successCount = 0;
  let errorCount = 0;
  let notFoundCount = 0;
  
  for (const imgPath of URGENT_IMAGES) {
    try {
      console.log(`\n处理: ${imgPath}`);
      console.log('-'.repeat(50));
      
      const result = await compressUrgentImage(imgPath);
      
      if (result.status === 'success') {
        totalOriginalSize += result.originalSize;
        totalNewSize += result.newSize;
        successCount++;
      } else if (result.status === 'error') {
        errorCount++;
      } else if (result.status === 'not_found') {
        notFoundCount++;
      }
    } catch (error) {
      console.error(`处理出错:`, error);
      errorCount++;
    }
  }
  
  console.log('\n========== 紧急图片处理完成 ==========');
  console.log(`总图片数: ${URGENT_IMAGES.length}`);
  console.log(`成功处理: ${successCount}`);
  console.log(`处理失败: ${errorCount}`);
  console.log(`文件不存在: ${notFoundCount}`);
  
  if (successCount > 0) {
    const totalReduction = totalOriginalSize - totalNewSize;
    const reductionPercent = (totalReduction / totalOriginalSize) * 100;
    
    console.log(`\n总体积变化: ${totalOriginalSize.toFixed(2)}KB -> ${totalNewSize.toFixed(2)}KB`);
    console.log(`总减少: ${totalReduction.toFixed(2)}KB (${reductionPercent.toFixed(2)}%)`);
  }
  
  console.log('\n下一步:');
  console.log('1. 使用微信开发者工具的"详情 -> 基础库 -> 代码体积分析"检查主包大小');
  console.log('2. 上传小程序到微信平台');
  console.log('3. 如果仍然超过大小限制，考虑将大图片移至云存储');
}

// 执行主函数
main().catch(error => {
  console.error('紧急处理脚本执行失败:', error);
}); 